package com.tmsps.ne4weixin.api;

import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tmsps.ne4weixin.bean.BaseResultBean;
import com.tmsps.ne4weixin.config.WxConfig;
import com.tmsps.ne4weixin.utils.WXHttpUtil;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Title: UserTagAPI.java
 * @Package: com.tmsps.ne4weixin.api
 * @Description: 用户标签管理API
 * @author: hanjiefei
 * @date: 2019-10-22
 * @version V1.0
 * @Copyright: 2019
 */
@Slf4j
public class UserTagAPI extends BaseAPI {

	public UserTagAPI(WxConfig wxConfig) {
		super(wxConfig);
	}
	
	public String createTag(String name) {
		if (StrUtil.isBlank(name) || StrUtil.length(name) >= 30) {
			log.error("tag的名称不能为空,或者长度小于30.");
			return null;
		}
		String url = String.format(CREATE_TAG, wxConfig.getAccessToken());
		JSONObject tagName = new JSONObject();
		tagName.put("name", name);
		JSONObject tagJson = new JSONObject();
		tagJson.put("tag", tagName);
		String result = WXHttpUtil.postJson(url, tagJson.toJSONString());
		return result;
	}
	

	/**
	 * 批量为用户打标签
	 * 
	 * @param tagId       标签id
	 * @param openid_list 粉丝列表
	 * @return
	 */
	public BaseResultBean addTagToMember(Integer tagId, List<String> openid_list) {
		String url = String.format(BATCH_TAGS, wxConfig.getAccessToken());
		JSONObject tagJson = new JSONObject();
		tagJson.put("tagid", tagId);
		tagJson.put("openid_list", openid_list);
		String result = WXHttpUtil.postJson(url, tagJson.toJSONString());
		log.info("批量为用户打标签返回信息:{}", result);
		return JSONObject.parseObject(result, BaseResultBean.class);
	}

	/**
	 * 批量为用户取消标签
	 * 
	 * @param tagId       标签id
	 * @param openid_list 粉丝列表
	 * @return
	 */
	public BaseResultBean cancleMemberTag(Integer tagId, List<String> openid_list) {
		String url = String.format(BATCH_UNTAGS, wxConfig.getAccessToken());
		JSONObject tagJson = new JSONObject();
		tagJson.put("tagid", tagId);
		tagJson.put("openid_list", openid_list);
		String result = WXHttpUtil.postJson(url, tagJson.toJSONString());
		log.info("批量为用户取消标签返回信息:{}", result);
		return JSONObject.parseObject(result, BaseResultBean.class);
	}

	/**
	 * 获取用户身上的标签列表
	 * 
	 * @param openid 用户openid
	 * @return
	 */
	public JSONArray getMemberTagList(String openid) {
		String url = String.format(GET_ID_LIST, wxConfig.getAccessToken());
		JSONObject tagJson = new JSONObject();
		tagJson.put("openid", openid);
		String result = WXHttpUtil.postJson(url, tagJson.toJSONString());
		log.info("获取用户身上的标签列表返回信息:{}", result);
		JSONObject end = JSONObject.parseObject(result);
		return end.getJSONArray("tagid_list");
	}

}
